package com.adminx.dao.impl;

import com.adminx.utils.ResourceConstants;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;

public abstract class BaseDao {

    private Logger logger = LogManager.getLogger(BaseDao.class) ;
    protected Connection conn = null ;
    protected ResultSet rs = null ;
    protected PreparedStatement ps = null ;


    protected Connection getConnection() {
        try {
            if (conn == null || conn.isClosed()) {

                Class.forName(ResourceConstants.MYSQL_DRIVER);
                conn = DriverManager.getConnection(ResourceConstants.MYSQL_URL, ResourceConstants.MYSQL_USER, ResourceConstants.MYSQL_PWD);
                logger.info(" A new connection was got.") ;
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return this.conn ;
    }
    protected void doQuery(String sql, Object ... params) {
        try {
            this.conn = getConnection();
            this.ps = conn.prepareStatement(sql) ;
            injectParam(ps, params);
            logger.info("do query for sql: {} for parameters: {}", sql, params) ;
            this.rs = this.ps.executeQuery() ;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void close() {
        try {
            if (rs != null) {
                rs.close();
            }
            if (ps != null) {
                ps.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("A connection was failed in close.");
        }
        logger.info(" A connection was closed.") ;

    }
    private void injectParam(PreparedStatement ps, Object... params) throws Exception {

        if (params!= null && params.length > 0 ) {
            for (int i=1; i<=params.length; i++) {
                if (params[i-1] == null) {
                    continue ;
                }
                ps.setObject(i, params[i-1]);
            }
        }
    }

    protected int doUpate(String sql, Object... params ) {
        try {
            getConnection();
            ps = conn.prepareStatement(sql) ;
            injectParam(ps, params);
            return ps.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close();
        }
        return 0 ;
    }

}
